package com.ruoyi.common.satoken.config;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.strategy.SaStrategy;
import cn.dev33.satoken.util.SaFoxUtil;
import com.ruoyi.common.satoken.core.dao.PlusSaTokenDao;
import com.ruoyi.common.satoken.core.service.SaPermissionImpl;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * Sa-Token 配置
 *
 * @author Lion Li
 */
@AutoConfiguration
public class SaTokenConfiguration {

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

    /**
     * 权限接口实现(使用bean注入方便用户替换)
     */
    @Bean
    public StpInterface stpInterface() {
        return new SaPermissionImpl();
    }

    /**
     * 自定义dao层存储
     */
    @Bean
    public SaTokenDao saTokenDao() {
        return new PlusSaTokenDao();
    }


    /**
     * 重写 Sa-Token 框架内部算法策略
     */
    @Autowired
    public void rewriteSaStrategy() {
        // 重写 Token 生成策略
//        SaStrategy.instance.createToken = (loginId, loginType) -> {
//            // todo 自定义生成token策略
//            String randomString = SaFoxUtil.getRandomString(60);
//            return randomString;
//        };

        SaStrategy.instance.generateUniqueToken = (elementName, maxTryTimes, createTokenFunction, checkTokenFunction) -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            LoginUser loginUser = (LoginUser)request.getAttribute("login_info");
            StringBuilder sb = new StringBuilder();
            if (loginUser != null) {
                sb.append(loginUser.getUserId()+"");
//                sb.append(":");
//                sb.append(loginUser.getUsername());
                sb.append(":");
                sb.append(loginUser.getUserType());
                sb.append(":");
                sb.append(LocalDateTime.now().toString());
                sb.append(":");
            }
            sb.append(uuid);
            return sb.toString();
        };
    }

}
